import { createSlice } from '@reduxjs/toolkit';

export const todoListSlice = createSlice({
  name: 'todoList',
  initialState: {
    isShowAddInput: false,
    todoList: JSON.parse(localStorage.getItem('todoListWithRedux') || '[]'),
    isShowModal: false,
    modalTitle: '',
    modalContent: {},
    filter: 'all',
  },
  reducers: {
    setIsShowAddInput: (state, action) => {
      state.isShowAddInput = action.payload;
    },
    addTodo: (state, action) => {
      state.todoList.push({
        id: new Date().getTime(),
        completed: false,
        title: action.payload
      })
    },
    toggleTodo: (state, {type, payload}) => {
      state.todoList.forEach(obj => {
        if (obj.id === payload) {
          obj.completed = !obj.completed
        }
      })
    },
    delTodo: (state, {type, payload}) => {
      state.todoList = state.todoList.filter(obj => obj.id !== payload)
    },
    setIsShowModal: (state, action) => {
      state.isShowModal = action.payload
    },
    setModalTitle: (state, { type, payload }) => {
      state.modalTitle = payload
    },
    setModalContent: (state, { type, payload }) => {
      state.modalContent = payload
    },
    editTodo: (state, { type, payload }) => {
      const { id, title } = payload
      state.todoList.forEach(obj => {
        if (obj.id === id) {
          obj.title = title
        }
      })
    },
    setFilter: (state, {type, payload}) => {
      state.filter = payload
    }
  }
});

export const { setIsShowAddInput, addTodo, toggleTodo, delTodo, setIsShowModal, setModalTitle, setModalContent, editTodo, setFilter } = todoListSlice.actions;
export default todoListSlice.reducer;
